// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
// 返回工具类
const returnUtil = require('utils/ReturnUtil.js')
// 商品信息业务层
const product = require('service/productService.js')  
// 轮播业务层
const banner = require('service/bannerService.js')
// 主题业务层
const theme  = require('service/themeService.js')
const order = require('service/orderService.js')
const admin = require('service/adminService.js')
const category = require('service/categoryService.js');
const area = require('service/areaService.js');
const address = require('service/addressService.js')
const notice = require('service/noticeService.js')
const printer = require('service/printerService.js')
const signIn = require('service/signInService.js')
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: 'ibookshop-1wxto'
  
})
const IMAGEPREFIX = "cloud://ibookshop-1wxto.6962-ibookshop-1wxto-1303227463"

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const app = new TcbRouter({ event });
  // app.use 表示该中间件会适用于所有的路由
  app.use(async (ctx, next) => {
    ctx.data = {};
    await next(); // 执行下一中间件
  });
 /************************** 管理员后台登录 ******************/
  app.router('getAdmin', async (ctx, next) => {
   ctx.data = await admin.getAdmin()
   ctx.body = await returnUtil.success(ctx)
   await next();
 })
//  管理员修改用户名或密码
 app.router('updateAdmin', async (ctx, next) => {
    let admin1 = event.data.admin
    let adminId = event.data.adminId
    ctx.data = await admin.updateAdmin(admin1, adminId)
    ctx.body = await returnUtil.success(ctx)
 await next();
})

  /************************** 新增商品 ******************/
  app.router('addProduct',async (ctx, next) => {
    let product1 =  event.data.product
    ctx.data = await product.addProduct(product1)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  app.router('getOpenId', async (ctx, next) => {
    // banner.getBanner() 取出数据，然后对数据进行重新拼装
    let openid = wxContext.OPENID
   ctx.data = {openId:openid}
   ctx.body = await returnUtil.success(ctx)
   await next();
 })
 /***************************    首页   *****************************************/
  // 获取轮播
  app.router('getBanner', async (ctx, next) => {
    // banner.getBanner() 取出数据，然后对数据进行重新拼装
    let openid = wxContext.OPENID
    console.log('ctxx',ctx)
   ctx.data = await _bannerItem(banner.getBanner())
   ctx.body = await returnUtil.success(ctx)
   await next();
 })
 // 获取主题
 app.router('getTheme',async (ctx,next) => {
   ctx.data = await _themeItem(theme.getTheme())
   ctx.body = await returnUtil.success(ctx)
   await next()
 })
  // 获取最新前5商品
  app.router('getProduct',async (ctx,next) => {
    // product.getProduct({},0,4)  {}：没有条件直接控{}，0，4 分页查询 
    ctx.data = await _productItem(product.getProduct({},0,100))
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  //修改商品
  app.router('updateProduct',async (ctx,next) => {
    let product1 = event.data.product
    let productId = event.data.productId
    console.log('p1',product1)
    ctx.data = await product.updateProduct(product1,productId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
    //模糊查询商铺
    app.router('regQuery',async (ctx,next) => {
      let regexp = event.data.regexp
      let columns = event.data.columns
      ctx.data = await _productItem(product.regQuery(regexp, columns))
      ctx.body = await returnUtil.success(ctx)
      await next()
    })

    //删除商品
    app.router('delProduct',async (ctx,next) => {
      let productId = event.data.productId
      console.log('pID',productId)
      ctx.data = await product.delProduct(productId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 添加商品种类
    app.router('addCategory',async (ctx,next) => {
      let category1 = event.data.category
      console.log('pID',category1)
      ctx.data = await category.addCategory(category1)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 删除商品种类
    app.router('delCategory',async (ctx,next) => {
      let categoryId = event.data.categoryId
      console.log('cID',categoryId)
      ctx.data = await category.delCategory(categoryId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    
     // 获取area
     app.router('getAreaList',async (ctx,next) => {
      ctx.data = await area.getAreaList()
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 获取收货地址

    app.router('getAddressList2',async (ctx,next) => {
      let openId = event.data.openId
      ctx.data = await address.getAddressList(openId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 添加收货地址
    app.router('addAddress2',async (ctx,next) => {
      let openId = event.data.openId
      let address1 = event.data.address
      console.log('add',address1)
      ctx.data = await address.addAddress(address1, openId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 重置地址数据库
    app.router('resetAddress2',async (ctx,next) => {
      let openId = event.data.openId
      ctx.data = await address.resetAddress(openId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 设置默认地址
    app.router('setDefaultAddress',async (ctx,next) => {
      let addressId = event.data.addressId
      ctx.data = await address.setDefaultAddress(addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 查询地址
    app.router('getAddressById',async (ctx,next) => {
      let addressId = event.data.addressId
      ctx.data = await address.getAddressById(addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
     // 修改地址
     app.router('modifyAddress',async (ctx,next) => {
      let addressId = event.data.addressId
      let address1 = event.data.address
      ctx.data = await address.modifyAddress(address1, addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
     // 删除地址
     app.router('delAddress',async (ctx,next) => {
      let addressId = event.data.addressId
      ctx.data = await address.delAddress(addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
   
    
 // 获取最新前5商品
 app.router('getProductNew',async (ctx,next) => {
   // product.getProduct({},0,4)  {}：没有条件直接控{}，0，4 分页查询 
   ctx.data = await _productItem(product.getProduct({},0,4))
   ctx.body = await returnUtil.success(ctx)
   await next()
 })

// 轮播图片地址拼接
 function _bannerItem(data){
   return new Promise((resolve,reject) => {
     data.then(res=>{
       res.data.forEach(data => {
         data.image = IMAGEPREFIX + data.image
       })
       resolve(res)
     })
   }) 
 }
// 主题图片地址拼接
 function _themeItem(data){
   return new Promise((resolve,reject) => {
     data.then(res=>{
       res.data.forEach(data => {
         data.theme_icon = IMAGEPREFIX + data.theme_icon
       })
       resolve(res)
     })
   }) 
 }
// 多个商品图片地址拼接
 function _productItem(data){
   return new Promise((resolve,reject) => {
     data.then(res=>{
       let products = res.data 
       for(let i=0;i<products.length;i++){
        let productImages = products[i].product_imgs
        let detailImages = products[i].detail_imgs
        console.log('porduct',productImages)
        for(let i=0;i<productImages.length;i++){
          productImages[i] = IMAGEPREFIX + productImages[i]
        }
        for(let i=0;i<detailImages.length;i++){
          detailImages[i] = IMAGEPREFIX + detailImages[i]
        }
       }
  
       resolve(res)
     })
   }) 
 }

 function _spliceImg(array){
   for(let i=0;i<array.length;i++){
     array[i] = IMAGEPREFIX + array[i]
   }
 }

   // 单个商品图片地址拼接
   function _productImg(data) {
    return new Promise((resolve, reject) => {
      data.then(res => {
        let productImages = res.data.product_imgs
        let detailImages = res.data.detail_imgs
        for(let i=0;i<productImages.length;i++){
          productImages[i] = IMAGEPREFIX + productImages[i]
        }
        for(let i=0;i<detailImages.length;i++){
          detailImages[i] = IMAGEPREFIX + detailImages[i]
        }
        
        resolve(res)
      })
    })
  }
 /***************************    分类   *****************************************/
  // 获取分类
  app.router('getCategoryMenu', async (ctx,next) =>{
    console.log('event',event.userInfo)
    ctx.data = await product.getCategoryMenu()
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
  // 获取分类商品
  app.router('getCategoryProduct', async (ctx , next) => {
    let options = {}
    // ctx.data 前台传过来的category_type
    options.category_type = event.data
    ctx.data = await _productItem(product.getCategoryProduct(options))
    ctx.body = await returnUtil.success(ctx)
    await next()
  })


/***************************    商品信息   *****************************************/  
// 获取商品信息
app.router('getProductById', async (ctx,next) =>{
  console.log('data:',event)
  let product_id =  event.data.product_id
  ctx.data = await _productImg(product.getProductById(product_id))
  ctx.body = await returnUtil.success(ctx)
  await next()
})


/***************************    主题商品   *****************************************/  
// 获取主题商品列表
app.router('getThemeProduct', async (ctx,next) =>{
  // 前台传入主题类型    
  let theme_type = event.data.theme_type
  ctx.data = await _productItem(product.getThemeProduct(theme_type))
  ctx.body = await returnUtil.success(ctx)
  await next()
})

  /***************************    订单   *****************************************/
  // 生成订单
  app.router('creatOrder', async (ctx, next) => {
    ctx.data = await order.create(event.data.orderData)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
   // 删除订单
   app.router('delOrder',async (ctx,next) => {
    let orderId = event.data.orderId
    ctx.data = await order.delOrder(orderId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
  // 根据订单获取信息
  app.router('getOrderById', async (ctx, next) => {
    let orderId = event.data.orderId
    ctx.data = await order.getOrderById(orderId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  // 获取订单信息
  app.router('getOrderList', async (ctx, next) => {
    let openId = event.data.openId
    ctx.data = await order.getOrderList(openId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

   // 获取所有订单信息
   app.router('getOrders', async (ctx, next) => {
    ctx.data = await order.getOrders()
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
 

  // 更新订单 
  app.router('updateOrder', async (ctx, next) => {
    let orderId = event.data.orderId
    let order1 = event.data.order
    ctx.data = await order.updateOrder(orderId, order1)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })


/***************************    主题   *****************************************/    
  app.router('getTheme', async (ctx, next) => {
    ctx.data = await _themeItem(theme.getTheme())
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  app.router('addTheme', async (ctx, next) => {
    let theme = event.data.theme
    ctx.data = await theme.addTheme(theme)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  app.router('delTheme', async (ctx, next) => {
    let theme_id = event.data.theme_id
    ctx.data = await theme.delTheme(theme_id)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  app.router('getThemeProduct', async (ctx, next) => {
    let theme_type = event.data.theme_type
    ctx.data = await _productItem(product.getThemeProduct(theme_type))
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
/***************************    banner   *****************************************/    

  app.router('getBanners',async(ctx, next)=>{
    ctx.data = await _bannerItem(banner.getBanners())
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  app.router('addBanner',async(ctx, next)=>{
    let banner1 = event.data.banner
    ctx.data = await banner.addBanner(banner1)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  app.router('delBanner',async(ctx, next)=>{
    let bannerId = event.data.bannerId
    ctx.data = await banner.delBanner(bannerId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
/***************************    notice   *****************************************/    

  app.router('addNotice', async(ctx, next) => {
    let notice1 = event.data.notice
    ctx.data = await notice.addNotice(notice1)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })


   //获取公告
   app.router('getNotice',async (ctx,next) => {
    ctx.data = await notice.getNotice()
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

   //获取公告
   app.router('getNoticeById',async (ctx,next) => {
    let noticeId = event.data.noticeId
    ctx.data = await notice.getNoticeById(noticeId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
  //更新公告
  app.router('updateNotice',async (ctx,next) => {
    let notice1 = event.data.notice
    let noticeId = event.data.noticeId
    console.log('notice',notice1)
    ctx.data = await notice.updateNotice(notice1, noticeId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
  //删除公告
  app.router('delNotice',async (ctx,next) => {
    let noticeId = event.data.noticeId
    ctx.data = await notice.delNotice(noticeId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
 /***************************    地址   *****************************************/    
     // 获取area
     app.router('getAreaList',async (ctx,next) => {
      ctx.data = await area.getAreaList()
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 获取收货地址

    app.router('getAddressList',async (ctx,next) => {
      let openId = event.data.openId
      ctx.data = await address.getAddressList(openId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 添加收货地址
    app.router('addAddress',async (ctx,next) => {
      let openId = event.data.openId
      let address1 = event.data.address
      console.log('add',address1)
      ctx.data = await address.addAddress(address1, openId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 重置地址数据库
    app.router('resetAddress',async (ctx,next) => {
      let openId = event.data.openId
      ctx.data = await address.resetAddress(openId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 查询地址
    app.router('getAddressById',async (ctx,next) => {
      let addressId = event.data.addressId
      ctx.data = await address.getAddressById(addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
     // 修改地址
     app.router('modifyAddress',async (ctx,next) => {
      let addressId = event.data.addressId
      let address1 = event.data.address
      ctx.data = await address.modifyAddress(address1, addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
     // 删除地址
     app.router('delAddress',async (ctx,next) => {
      let addressId = event.data.addressId
      ctx.data = await address.delAddress(addressId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
/***************************    打印机  *****************************************/    
    
     // 查询打印机
     app.router('getPrinter',async (ctx,next) => {
      ctx.data = await printer.getPrinter()
      ctx.body = await returnUtil.success(ctx)
      await next()
    })
    // 更新打印机信息
    app.router('updatePrinter',async (ctx,next) => {
      let printer1 = event.data.printer
      let printerId = event.data.printerId
      ctx.data = await printer.updatePrinter(printer1, printerId)
      ctx.body = await returnUtil.success(ctx)
      await next()
    })

   /***************************    日历  *****************************************/    
  
   //  1、获取用户已签到日期
   app.router('getCalendar',async (ctx,next) => {
    let calendar = event.data.calendar
    ctx.data = await signIn.getCalendar(calendar)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
  // 2、更新本月签到信息
  app.router('updateCalendar',async (ctx,next) => {
    let calendar = event.data.calendar
    let calendarId = event.data.calendarId

    ctx.data = await signIn.updateCalendar(calendar, calendarId)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })
  // 3、新增本月签到数据
  app.router('addCalendar',async (ctx,next) => {
    let calendar = event.data.calendar
    ctx.data = await signIn.addCalendar(calendar)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })

  /***************************    顾客信息  *****************************************/

  // 1、添加用户数据
  app.router('addCustomer',async (ctx,next) => {
    let customer = event.data.calendar
    ctx.data = await Customer.addCustomer(customer)
    ctx.body = await returnUtil.success(ctx)
    await next()
  })



  return app.serve();
}
